import {onMounted} from "vue";
import http from "@/utils/request";
import {ElMessage} from "element-plus";
import {useRoute, useRouter} from "vue-router";

export function useUpdate(model,form,ruleForm,afterCallBack) {
    const router = useRouter();
    const route = useRoute()


    onMounted(async () => {
        let id = route.query.id;
        let data = {};
        data.id = id;
        let res = await http.post(`/${model}/view`, data);
        if (res.code === 200) {
            form.value = res.data;
            if (afterCallBack){
                afterCallBack(res.data);
            }
        }
    })

    const updateData = async () => {
       let res= await updateStaging();
       if (!res){
           return;
       }
        router.go(-1);
    }

    const updateStaging = async () => {
        let res = await http.post(`/${model}/update`, form.value);
        if (res.code !== 200) {
            ElMessage.error(res.msg)
            return false;
        }
        ElMessage({
            message: '更新数据成功',
            type: 'success',
        })
        return true;
    }
    const  goBack=()=> {
        router.go(-1);
    }
    return {updateData,goBack,updateStaging}

}
